package cn.wenhaha.app.config;

import cn.dev33.satoken.interceptor.SaAnnotationInterceptor;
import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    // 注册Sa-Token的注解拦截器，打开注解式鉴权功能
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册注解拦截器，并排除不需要注解鉴权的接口地址 (与登录拦截器无关)
        registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");

        //路由拦截
        registry.addInterceptor(new SaMyRouteInterceptor())
                .addPathPatterns("/plugins/**");
    }

    private  static  class SaMyRouteInterceptor extends SaRouteInterceptor {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            try {
                return super.preHandle(request, response, handler);
            } catch (Exception e) {
                e.printStackTrace();
                // 停止匹配，向前端输出结果
                if(response.getContentType() == null) {
                    response.setContentType("text/plain; charset=utf-8");
                }
                response.getWriter().print(e.getMessage());
                return false;
            }
        }
    }
}       